<template>
	<view class="content" :style="{height:pageConfig.scrollHeight}">
		<z-paging ref="paging" :refresher-only="true" refresher-theme-style="white" :fixed="false" @query="getPageData">
			<template #top>
				<u-navbar style="z-index: 99;" :fixed="false" :safeAreaInsetTop="true">
					<!-- 蓝牙设备下拉 -->
					<view class="u-nav-slot comboSelect" slot="left">
						<uni-data-select placeholder="请添加设备" v-model="CheckHisValue" :localdata="HistoryDeviceList"
							iconColor="#fff" :clear="false" @change="ChangeAgreement"></uni-data-select>
					</view>
					<view class="u-nav-slot" slot="right">
						<m-capsule></m-capsule>
					</view>
				</u-navbar>
			</template>

			<m-drag-button v-if="ToDoPermissions" :isDock="true" :existTabBar="true" :initialBottom="160"
				@btnClick="goToDo()">
				<template #BtnContent>
					<!-- <u-icon name="chat-fill" color="#fff" size="54rpx"></u-icon> -->
					<text style="font-size:14px;color:#fff;">待办</text>
				</template>
			</m-drag-button>

			<view class="MainBox">

				<view class="TopBac">
					<view class="CardBox">
						<view class="CardStyle">

							<view class="LeftTitle"
								style="display: flex;justify-content: space-between;align-items: center;">
								<text>统计数据</text>

								<text style="font-size: 13px;color: #999;margin-right: 20rpx;"
									@click="ToSeeMore">更多>></text>
							</view>

							<!-- 环形图 -->
							<view class="ChartBox">

								<view style="flex: 1;">
									<view class="charts-box">
										<qiun-data-charts type="ring" :opts="Charts.opts"
											:chartData="Charts.chartData"></qiun-data-charts>
									</view>
								</view>

								<view class="RightTextBox">
									<view class="GridBox">
										<uni-row class="GridCard">
											<uni-col :span="12">
												<view>
													<text class="CommonText"
														style="color: #FAC858;">{{ChartsData.WJYSL || 0}}</text>
													<text class="CommonText BotText">未检验数</text>
												</view>
											</uni-col>
											<uni-col :span="12">
												<view>
													<text class="CommonText"
														style="color: #52aeff;">{{ChartsData.JYSL}}</text>
													<text class="CommonText BotText">已检验数</text>
												</view>
											</uni-col>
											<uni-col :span="12" style="margin-top: 12px;">
												<view>
													<text class="CommonText"
														style="color: #91CB74;">{{ChartsData.HGNumber}}</text>
													<text class="CommonText BotText">合格数</text>
												</view>
											</uni-col>
											<uni-col :span="12" style="margin-top: 12px;">
												<view>
													<text class="CommonText"
														style="color: #fa231b;">{{ChartsData.BHGNumber}}</text>
													<text class="CommonText BotText">不合格数</text>
												</view>
											</uni-col>
										</uni-row>





									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 单据类型 -->
					<view class="CardBox">
						<view class="CardStyle">
							<view class="LeftTitle">
								<text>检验类型</text>
							</view>

							<view class="CardMain">
								<u-grid :border="false" col="4" style="padding-bottom: 10rpx;">
									<u-grid-item v-for="(item,index) in UsualModules" :key="index"
										@click="ToOther(item,index)">
										<!-- <uni-icons :color="item.Color" custom-prefix="iconfont" :type="item.IconImg"
											size="40"></uni-icons> -->
										<uni-icons fontFamily="CustomFontPlatform" :color="item.AP_Colour"
											:size="40">{{$utils.toUniCode(item.PIC_PH)}}</uni-icons>
										<text class="grid-text">{{item.APFunName}}</text>
									</u-grid-item>
								</u-grid>

							</view>
						</view>
					</view>
				</view>

				<!-- 历史设备 -->
				<view class="CardBox HisCardBox" v-show="HistoryDeviceList.length">
					<view class="CardStyle">
						<view class="LeftTitle">
							<text>历史设备</text>
						</view>

						<view class="CardMain" style="padding: 0 10px;">

							<u-scroll-list :indicator="false">
								<view class="UsualCard" v-for="(item,index) in HistoryDeviceList" :key="index"
									style="zoom: .8;" @click="CheckTabbar(item,index)">

									<view style="flex: 1;min-width: 140px;">

										<!-- 设备名称 -->
										<view style="margin-top: 8px;">
											<text style="font-weight: 600;">{{item.DeviceName}}</text>
										</view>
										<view style="margin-top: 14px;font-size: 13px;">
											<text>型号：</text>
											<text>{{item.MeasureSpec}}</text>
										</view>
									</view>

									<!-- Logo -->
									<view>
										<u--image :showLoading="true" :src="judgeImg(item.FilePath)" mode="widthFix"
											width="40px" height="40px"></u--image>
									</view>
								</view>
							</u-scroll-list>
						</view>
					</view>
				</view>


				<!-- 检验单据 -->
				<view class="CardBox ListCardBox">
					<view class="CardStyle">
						<view class="LeftTitle">
							<text>检验单据</text>
						</view>

						<view class="CardMain">
							<view class="DocumentsList" style="padding: 8px 10px;">

								<uni-row v-if="DocumentsList.length" :gutter="20" class="CardInfo">
									<uni-col v-for="(item,index) in DocumentsList" :key="index" :span="24"
										:xs="{span: 24}" :sm="{span: 12}" style="margin-bottom: 10px;">
										<view class="DocumentsListCard" @click="OpenDocumentsInfo(item)">
											<view class="ordinal">
												{{index+1}}
											</view>

											<!-- 单据状态 目前： 是否已检验 -->
											<view class="TypeTextBox"
												:class="item.SFJYName == '已检验' ? 'HGStyle' : 'BHGStyle'">
												<text>{{item.SFJYName}}</text>
											</view>

											<view class="CodeText">
												<text class="lebelText">单据编号：</text>
												<text class="valueText">{{item.BillNO}}</text>
											</view>
											<view class="DocumentsTopInfo">
												<view class="RowFlex">
													<text class="lebelText">单据类型：</text>
													<text class="valueText">{{item.FType}}</text>
												</view>

												<view class="RowFlex">
													<text class="lebelText">单据日期：</text>
													<text class="valueText">{{item.BillDate}}</text>
												</view>
											</view>
											<view class="DocumentsTopInfo">
												<view class="RowFlex">
													<text class="lebelText">来料数量：</text>
													<text class="valueText">{{item.BJNum}}</text>
												</view>

												<view class="RowFlex">
													<text class="lebelText">合格数量：</text>
													<text class="valueText">{{item.HGNumber}}</text>
												</view>
											</view>
											<view class="DocumentsTopInfo">
												<view class="RowFlex">
													<text class="lebelText">检验人员：</text>
													<text class="valueText">管理员</text>
												</view>

												<view class="RowFlex" v-if="index == 2">
													<text class="lebelText">审核日期：</text>
													<text class="valueText">2023-09-20 10:30:06</text>
												</view>
											</view>
										</view>

									</uni-col>
								</uni-row>


								<u-empty v-else text="暂无检验数据" mode="list"></u-empty>

							</view>


						</view>
					</view>
				</view>
			</view>



			<!-- <template #bottom>
				<qms-tabbar style="z-index: 99;" :current-page="0"></qms-tabbar>
			</template> -->
		</z-paging>


		<!-- 导航栏右侧按钮 -- 遮罩层 -->
		<u-overlay :show="ShowRightNav" v-if="ShowRightNav" @click="ShowRightNav = false" opacity="0.4">
			<view class="warp">
				<view class="rect" @tap.stop>
					<u-cell title="添加设备" @click="AddBtn">
						<u-icon slot="icon" size="16" name="plus"></u-icon>
					</u-cell>
					<u-cell title="扫一扫" @click="ToScan">
						<u-icon slot="icon" size="20" name="scan"></u-icon>
					</u-cell>
				</view>
			</view>
		</u-overlay>

	</view>
</template>

<script>
	export default {
		props: {
			config: {
				type: Object,
				default: () => ({
					tabbarHeight: 0,
					scrollHeight: 500
				})
			},
			isPage: {
				type: Boolean,
				default: true
			},
		},

		data() {
			return {
				IsDemo: false, // 是否是演示账套
				ShowRightNav: false, // 导航栏右侧侧下拉
				myChart: null,
				UsualModules: [], // 常用单据模块
				ColSpan: 12,
				ChartsData: {},
				Charts: {
					chartData: {},
					opts: {
						rotate: false, // 横屏模式
						rotateLock: false, // 横屏锁定模式
						color: ["#FAC858", "#52aeff", "#91CB74", "#fa231b", "#999999", "#73C0DE", "#3CA272", "#FC8452",
							"#9A60B4", "#ea7ccc"
						],
						padding: [0, 0, 0, 0],
						dataLabel: false, // 图文连接线
						enableScroll: false,
						legend: { // 图例
							show: false,
							position: "right",
							lineHeight: 10
						},
						title: {
							name: "检验数据",
							fontSize: 15,
							color: "#666666"
						},
						subtitle: {
							name: "",
							fontSize: 25,
							color: "#7cb5ec"
						},
						extra: {
							ring: {
								ringWidth: 30, //	圆环的宽度
								activeOpacity: 0.5, // 启用Tooltip点击时，突出部分的透明度
								activeRadius: 10, // 启用Tooltip点击时，突出部分的宽度（最大值不得超过labelWidth）
								offsetAngle: 0, // 起始角度偏移度数
								labelWidth: 0, // 数据标签到饼图外圆连线的长度
								border: true, // 是否绘制各类别中间的分割线
								borderWidth: 2, // 分割线的宽度
								borderColor: "#FFFFFF", // 分割线的颜色
							},
						}
					}
				},
				DocumentsList: [], // 检验单据
				TypeMap: {},
				ToDoPermissions: false,

			}
		},
		computed: {
			pageConfig() {
				const config = this.$utils.deepClone(this.config);
				if (this.isPage) {

					config.scrollHeight = `100vh`;
				} else {
					config.scrollHeight = `${config.scrollHeight}px`;
				}
				return config;
			},

			HistoryDeviceList() {
				return this.$store.getters['QmsModule/DeviceHistory'];
			},

			CheckHisValue: {
				get() {
					return this.$store.state.QmsModule.DeviceLinkConfig.CheckHisValue || 0;
				},
				set(value) {
					this.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.CheckHisValue',
						data: value,
						StorageName: 'CheckHisValue',
						StorageData: value
					});
				}
			},

			selectedAgreement() {
				if (!this.HistoryDeviceList.length || this.CheckHisValue >= this.HistoryDeviceList.length) {
					return {};
				}
				return this.HistoryDeviceList[this.CheckHisValue];
			}
		},

		created() {
			this.initScreenWidth();
			this.IsDemo = uni.getStorageSync('App_demo') || false;
			uni.hideToast();
			this.getTypeMap();
			setTimeout(() => {
				this.getToDoPermissions();
				this.getPageData();
				this.initUsualModules();
			}, 300);
		},
		onShow() {
			if (this.isPage) {
				this.clearStorage();
				this.getPageData();
			}
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			getToDoPermissions() {
				let NData = this.$store.state.appConfigInfo.ModuleInfo_All[0]['Node'].filter(
					item => !item
					.IsTabbar);
				this.ToDoPermissions = NData.some((ele) => ele.APFunName == '审批待办')
			},
			getTypeMap() {
				this.Request.request('Get_QMS_FType', {}, (ret) => {
					if (ret.status === 200) {
						let arr = ret.data.ds
						arr.forEach((item) => {
							this.TypeMap[item.FType] = item.Name
						})
						console.log(this.TypeMap)
					}
				});
			},
			goToDo() {
				uni.navigateTo({
					url: '/commonPage/Module/todo' + '?source=QMS'
				});
			},
			initScreenWidth() {
				const systemInfo = uni.getSystemInfoSync();
				const windowWidth = systemInfo.windowWidth;

				if (windowWidth <= 500) {
					this.ColSpan = 12;
				} else if (windowWidth > 500 && windowWidth < 1000) {
					this.ColSpan = 8;
				}
			},

			initUsualModules() {
				const organizedData = this.$store.state.appConfigInfo.ModuleInfo_All
					.filter(item => !item.IsTabbar);

				this.UsualModules = organizedData
					.flatMap(item => item.Node.filter(row => !row.IsTabbar))
					.sort((a, b) => a.APFunCode - b.APFunCode)
					.slice(0, 4);
			},

			clearStorage() {
				uni.removeStorageSync('OrderUrl');
				uni.removeStorageSync('GetDocumentInfo');
			},

			onMyShow() {
				this.clearStorage();
				this.getPageData();
			},

			async getPageData() {
				try {
					await Promise.all([
						this.GetChartsInfo(),
						this.GetListArr()
					]);
				} catch (error) {
					console.error('Error fetching page data:', error);
				}
			},

			ToSeeMore() {
				uni.navigateTo({
					url: '/st_qms/index/stats'
				});
			},
			ToScan() { // 扫一扫
				this.$scanPopup.openScan({
					success: (res) => {
						console.log('条码内容：' + res.result);
					}
				})
				setTimeout(() => {
					this.ShowRightNav = false;
				}, 300);
			},
			GetChartsInfo() { // 获取环形图数据
				return new Promise((resolve) => {
					this.Request.request('APP_SYJK', {}, (ret) => {
						if (ret.status === 200) {
							const obj = ret.data.ds[0];
							if (!obj.hasOwnProperty('WJYSL')) {
								obj.WJYSL = 0;
							}
							this.ChartsData = obj;
							this.getServerData(obj);
						}
						setTimeout(() => {
							this.$refs.paging?.endRefresh();
							resolve();
						}, 100);
					});
				});
			},
			GetListArr() { // 获取最新检验单据
				return new Promise((resolve) => {
					this.Request.request('APP_SYJYSJJK', {}, (ret) => {
						if (ret.status === 200) {
							this.DocumentsList = [].concat(...Object.values(ret.data));

							let NData = this.$store.state.appConfigInfo.ModuleInfo_All[0]['Node'].filter(
								item => !item
								.IsTabbar);

							this.DocumentsList = this.DocumentsList.filter((item) => {
								let flag = false;
								flag = NData.some((ele) => ele.APFunName == this.TypeMap[item
									.FType])
								return flag;
							})
						}
						resolve();
					});
				});
			},
			judgeImg(data) {
				if (!data) return '';
				if (!/^http[s]?:\/\/.*/.test(data)) {
					return `${this.Request.IPAgreement()}${this.Request.serverIP()}${data}`;
				}
				return data;
			},
			getServerData(obj) { //模拟从服务器获取数据时的延时

				setTimeout(() => {
					const res = {
						series: [{
							data: [{
									name: "未检验数",
									value: obj.WJYSL,
									labelText: ""
								},
								{
									name: "已检验数",
									value: obj.JYSL,
									labelText: ""
								},
								{
									name: "合格数",
									value: obj.HGNumber,
									labelText: ""
								},
								{
									name: "不合格数",
									value: obj.BHGNumber,
									labelText: ""
								}
							]
						}]
					};
					this.Charts.chartData = JSON.parse(JSON.stringify(res));
				}, 500);
			},
			AddBtn() { // 添加设备
				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'RecordScan',
					data: true
				});
				this.ShowRightNav = false;
				uni.redirectTo({
					url: '/st_qms/control/control'
				});
			},
			CheckTabbar(data, index) {
				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.CheckHisValue',
					data: index,
					StorageName: 'CheckHisValue',
					StorageData: index
				});

				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'RecordScan',
					data: true
				});

				// uni.redirectTo({
				// 	url: '/st_qms/control/control'
				// });

				// 触发basicPage的切换事件
				this.$emit("basicPageFun", {
					pageType: "toControl"
				})
			},
			ChangeAgreement(index) {
				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.CheckHisValue',
					data: index,
					StorageName: 'CheckHisValue',
					StorageData: index
				});

				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'RecordScan',
					data: true,
				});

				// uni.redirectTo({
				// 	url: '/st_qms/control/control'
				// });
				// 触发basicPage的切换事件
				this.$emit("basicPageFun", {
					pageType: "toControl"
				})
			},
			OpenDocumentsInfo(data) {
				// const typeMap = {
				// 	'LLJYD': '来料检',
				// 	'SJJ': '首件检',
				// 	'MJJ': '末件检',
				// 	'CPJ': '成品检',
				// 	'XJ': '巡检'
				// };

				// const TheName = typeMap[data.FType];
				const TheName = this.TypeMap[data.FType];
				if (!TheName) return;
				let NData = this.$store.state.appConfigInfo.ModuleInfo_All[0]['Node'].filter(item => !item
					.IsTabbar);

				// const NData = JSON.parse(JSON.stringify(this.$store.state.QmsModule.NvoicesList));
				const FilterData = NData.filter(item => item.APFunName === TheName);
				if (FilterData.length) {
					uni.setStorageSync('OrderID', FilterData[0].APPFunID);
					uni.setStorageSync('GetDocumentInfo', JSON.stringify(data));

					plus.screen.lockOrientation('landscape-primary');

					setTimeout(() => {
						uni.navigateTo({
							url: '/st_qms/index/DocumentPage'
						});
					}, 300);
				}
			},
			ToOther(data, index) {
				if (this.IsDemo && index !== 0) {
					return uni.showToast({
						title: '该模块暂未授权',
						icon: 'error',
						duration: 2000
					});
				}
				if (data.AP_Link.includes('.html')) {
					uni.setStorageSync('OrderID', data.APPFunID);
					setTimeout(() => {
						uni.navigateTo({
							url: '/st_qms/index/DocumentPage'
						});
					}, 300)
				} else {
					setTimeout(() => {
						uni.navigateTo({
							url: data.AP_Link
						});
					}, 300)
				}
			}
		}
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	// 顶部右侧导航按钮样式
	.warp {
		display: flex;
		align-items: flex-start;
		height: 100%;
		justify-content: flex-end;

		.rect {
			min-width: 140px;
			min-height: 30px;
			background-color: #fff;
			border-radius: 12px;
			overflow: hidden;
			margin: 30px 12px 0 0;
		}
	}

	.content {
		display: flex;
		flex-direction: column;
		// height: 94vh;
		// background-color: #f9f9f9;

		background-image: linear-gradient(to bottom, rgba(81, 208, 208, 1), rgba(81, 208, 208, 1), rgba(81, 208, 208, 0.7) 30%, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0));
		/* 给顶部盒子安全高度 */
		// padding-top: var(--status-bar-height);

		// 公共样式-卡片
		.CardStyle {
			background-color: #fff;
			padding: 10px 0;
			border-radius: 12px;
		}
	}

	.comboSelect {

		::v-deep .uni-stat-box {
			background-color: transparent !important;
		}

	}

	::v-deep .uni-select {
		min-width: 150px;
		border: none !important;
		background-color: transparent !important;

		.uni-select__input-box {

			.uni-select__input-text,
			.uni-select__input-placeholder {
				color: #fff !important;
			}

			// 下拉框内文字样式
			::v-deep .uni-select__input-text {
				color: #fff !important;
				background-color: transparent !important;
			}

			.uni-icons {
				color: #fff !important;
			}
		}
	}

	.u-nav-slot {
		/* min-width: 80px; */
		width: fit-content;
	}


	// 顶部导航栏 navbar点击左侧会有改变透明的的操作，直接强制赋值为1
	.u-navbar__content__left {
		opacity: 1 !important;
	}

	/* .uni-select__selector {
		width: fit-content !important;
	} */

	.MainBox {
		flex: 1;
		overflow: auto;

		.TopBac {
			// background-image: linear-gradient(to bottom, rgba(81, 208, 208, 1), rgba(81, 208, 208, 0.7) 30%, rgba(255, 255, 255, 0));
			background-color: transparent;
		}

		.CardBox {
			padding: 15px;


			.ChartBox {
				display: flex;

				// charts图父盒子
				.charts-box {
					// width: 100%;
					width: 400rpx;
					height: 200px;
					// zoom: .6;
				}

				// 右侧图例盒子
				.RightTextBox {
					flex: 2;
					display: flex;
					align-items: center;

					.GridBox {
						.CommonText {
							display: block;
							text-align: center;
							font-size: 32rpx;
							font-weight: 600;
						}

						.BotText {
							margin-top: 14rpx;
							font-size: 20rpx;
							color: #999;
							font-weight: normal;
						}
					}
				}
			}



			// 标题
			.LeftTitle {
				height: 24rpx;
				line-height: 24rpx;
				font-size: 14px;
				font-weight: 600;
				margin-left: 8px;
			}

			// 内容
			.CardMain {
				margin-top: 10px;

				// 检验类型
				.grid-text {
					margin-top: 6px;
					font-size: 13px !important;
				}

				// 历史设备

				.UsualCard {
					display: flex !important;
					// position: relative; 
					// min-height: 100rpx;
					background-color: #f6f6f6;
					box-shadow: 1px 1px 13px -9px #999;
					align-items: center !important;
					margin-right: 10px !important;
					padding: 20px 15px !important;
					border-radius: 12px !important;
				}


				.UsualCardBox {

					// 组件在小程序端display为inline
					// QQ、抖音小程序文档写有 :host，但实测不生效
					// 百度小程序没有 :host
					/* #ifdef MP-TOUTIAO || MP-QQ || MP-BAIDU */
					display: block;
					/* #endif */


					.uni-col {
						margin-top: 10px;
						min-height: 100px;
					}
				}

				// 支付宝小程序没有 UsualCardBox 层级
				// 微信小程序使用了虚拟化节点，没有 UsualCardBox 层级
				/* #ifdef MP-ALIPAY || MP-WEIXIN */
				::v-deep .uni-row {
					margin-bottom: 10px;
				}

				/* #endif */

				.example-body {
					/* #ifndef APP-NVUE */
					display: block;
					/* #endif */
					padding: 5rpx 10rpx 0;
					overflow: hidden;
				}


				// 检验单据
				.DocumentsList {
					padding: 8px 10px;

					.DocumentsListCard {
						background-color: #f6f6f6;
						position: relative;
						border-radius: 12px;
						box-shadow: 1px 1px 12px -9px #333;
						min-height: 200px;
						padding: 10px 10px;
						width: 100%;
						margin: 0 auto;

						// 序号
						.ordinal {
							width: 20px;
							height: 20px;
							border-radius: 4px;
							line-height: 20px;
							background-color: #82cdff;
							text-align: center;
							color: #fff;
						}

						// 单据状态
						.TypeTextBox {
							width: fit-content;
							position: absolute;
							top: 30rpx;
							right: 10rpx;
							padding: 4rpx 6rpx;
							transform: rotate(45deg);
							border-radius: 12px;
						}

						.HGStyle {
							color: #51d0d0;
							border: 2px solid #51d0d0;
						}

						.BHGStyle {
							color: #999;
							border: 2px solid #999;
						}

						// 单据编号布局
						.CodeText {
							display: flex;
							align-items: center;
							margin-top: 6px;
							margin-bottom: 10rpx;
						}

						// 其他单据内容布局
						.DocumentsTopInfo {
							display: flex;
							justify-content: space-between;
							align-items: center;
							font-size: 14px;
							flex-wrap: wrap;


							.RowFlex {
								margin-top: 6px;
								flex: 1;
								display: flex;
								align-items: center;
								min-width: 200px;
							}
						}

						// 单据内容文字样式
						.lebelText {
							display: inline-block;
							// background-color: pink;
							width: 84px;
							font-size: 13px;
							color: #b1b1b1;
							/* 让文字均匀排布 */
							/*高度需要添加，不然文字下面会多出一些空隙*/
							text-align: justify;
							height: 20px;

							&::after {
								content: "";
								display: inline-block;
								width: 100%;
							}
						}

						.valueText {
							font-size: 13px;
						}
					}
				}
			}
		}

	}
</style>